<template>
  <div class="roles-wrap">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色区域 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-button type="primary" @click="isRolesdialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="rolesList" border stripe height="75vh">
        <!-- 栅格布局可视化，权限展示和删除 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 栅格布局 -->
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              :class="[index1 === 0 ? 'bgtop' : '', 'bgbottom', 'vcenter']"
            >
              <!-- 一级权限区域 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="deleteRightsForId(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级权限区域 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'bgtop', 'vcenter']"
                >
                  <!-- 渲染二级 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRightsForId(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="deleteRightsForId(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              type="primary"
              @click="openEdit(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              icon="el-icon-delete"
              type="danger"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              icon="el-icon-setting"
              type="warning"
              @click="openRightsBox(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹出层 -->
    <el-dialog
      title="添加角色"
      :visible.sync="isRolesdialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 添加角色表单 -->
      <el-form
        :model="newRoles"
        :rules="addrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="newRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="newRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加角色底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色弹出层 -->
    <el-dialog
      title="修改角色"
      :visible.sync="isEditDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 表单 -->
      <el-form
        :model="editRoles"
        :rules="addrules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出层 -->
    <el-dialog
      title="分配权限"
      :visible.sync="isShowRightDialogVisible"
      width="50%"
      @close="RightsClose"
    >
      <!-- 树形控件区域 -->
      <el-tree
        :data="rightTreeList"
        :props="defaultProps"
        :default-checked-keys="defaultCheckedArray"
        ref="treeRef"
        node-key="id"
        show-checkbox
        default-expand-all
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],
      // 权限树形Tree列表
      rightTreeList: [],
      // 添加角色显隐
      isRolesdialogVisible: false,
      // 编辑角色显隐
      isEditDialogVisible: false,
      // 分配角色显隐
      isShowRightDialogVisible: false,
      // 添加角色表单
      newRoles: {},
      // 编辑角色表单
      editRoles: {},
      // 校验规则
      addrules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ]
      },
      // 树形控件默认配置
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件默认选中数组
      defaultCheckedArray: [],
      // 确定后的权限 ID 列表
      strArrayRightId: [],
      // 当前选中的角色id
      checkRoleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    getRolesList () {
      this.$http.get('roles').then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('角色列表获取失败')
        this.rolesList = res.data.data
        // console.log(res.data.data)
      }).catch(err => {
        console.log(err)
      })
    },
    // 确定添加角色
    addRoles () {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return this.$message.error('添加角色失败')
        this.$http.post('roles', this.newRoles)
          .then(res => {
            console.log(res)
            if (res.data.meta.status !== 201) return this.$message.error('添加角色失败')
            this.$message.success('添加角色成功')
            this.isRolesdialogVisible = false
            this.getRolesList()
          }).catch(err => {
            console.log(err)
          })
      })
    },
    // 打开编辑角色框
    openEdit (id) {
      this.isEditDialogVisible = true
      this.$http.get('roles/' + id).then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('角色获取失败')
        this.editRoles = res.data.data
      }).catch(err => {
        this.$message.error('角色获取失败-by', err)
      })
    },
    // 确定编辑角色
    editUserInfo () {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return
        this.$http.put('roles/' + this.editRoles.roleId, this.editRoles).then(res => {
          this.$message.success('编辑成功')
          this.isEditDialogVisible = false
          this.getRolesList()
        }).catch(err => {
          console.log(err)
        })
      })
    },
    // 监听添加角色弹框关闭
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
      // this.getRolesList()
    },
    // 监听编辑角色弹框关闭
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 监听分配权限弹框关闭
    RightsClose () {
      this.defaultCheckedArray = []
    },
    // 删除角色
    deleteRoles (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败！请稍后再试！')
        this.getRolesList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 通过ID删除权限
    deleteRightsForId (role, rightsID) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$http.delete(`roles/${role.id}/rights/${rightsID}`)
          .then(res => {
            role.children = res.data.data
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      console.log(role, rightsID)
    },
    // 获取树形权限列表
    getRightTreeList () {
      this.$http.get('rights/tree')
        .then(res => {
          if (res.data.meta.status !== 200) return this.$message.error('获取权限列表失败')
          this.rightTreeList = res.data.data
        }).catch(err => {
          this.$message.error(err)
        })
      this.isShowRightDialogVisible = true
    },
    // 打开分配权限对话框
    openRightsBox (rights) {
      this.checkRoleId = rights.id
      this.getAllRights(rights, this.defaultCheckedArray)
      this.getRightTreeList()
    },
    // 通过递归获取所有三级权限的默认选中权限id
    getAllRights (rights, arr) {
      if (!rights.children) return arr.push(rights.id)
      rights.children.forEach(item => {
        this.getAllRights(item, arr)
      })
    },
    // 确定分配权限
    async submitRight () {
      const ArrayRightId = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      this.strArrayRightId = ArrayRightId.join(',')
      const { data: res } = await this.$http.post(`roles/${this.checkRoleId}/rights`, { rids: this.strArrayRightId })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败！')
      this.$message.success('分配权限成功!')
      this.getRolesList()
      this.isShowRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bgtop {
  border-top: 1px solid #ccc;
}
.bgbottom {
  border-bottom: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
